<?php

  define('ROOT_PATH', str_replace('admin/news_list.php', '', str_replace('\\', '/', __FILE__)));
  require_once(ROOT_PATH.'ty/TyUtils.php');
  require_once(ROOT_PATH.'ty/NewsService.php');
  require_once(ROOT_PATH.'ty/admin/categoryService.php');
  
  $smarty = TyUtils::getSmarty();
  
  $newsService = new NewsService();
  $categoryService = new CategoryService();
  
  $action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'news_list';
  
  if($action == 'news_list'){
      
      $newsList = $newsService->getAllNewsList();
      $smarty->assign('news_list', $newsList);
      
      $content = $smarty->fetch(ROOT_PATH.'templates/admin/news_list.inc');
      exit($content);
  }
  elseif($action == 'edit_news'){
      $newsId = $_REQUEST['news_id'];
      if(isset($newsId) && !empty($newsId)){
          $newsInfo = $newsService->getNewsInfoByNewsId($newsId);
          $smarty->assign('news_info', $newsInfo);
      }
      
      $cateOptions = $categoryService->buildCateOptionHtml($newsInfo['category_id']);
      $smarty->assign('cate_options', $cateOptions);
      
      $fckEditor = TyUtils::getFckEditor('news_content', $newsInfo['news_content']);
      $smarty->assign('fckeditor', $fckEditor);
      $content = $smarty->fetch(ROOT_PATH.'templates/admin/news_content.inc');
      exit($content);
  }
  elseif($action == 'save_news'){
      
      $newsId = isset($_REQUEST['news_id']) ? trim($_REQUEST['news_id']) : '';
      $newsTitle = isset($_REQUEST['news_title']) ? trim($_REQUEST['news_title']) : '';
      $newsCate = isset($_REQUEST['category_id']) ? trim($_REQUEST['category_id']) : '';
      $newsContent = isset($_REQUEST['news_content']) ? trim($_REQUEST['news_content']) : '';
      
      $newsInfo['news_id'] = $newsId;
      $newsInfo['news_title'] = addslashes($newsTitle);
      $newsInfo['category_id'] = $newsCate;
      $newsInfo['news_content'] = addslashes($newsContent);
      
      if(empty($newsId)){
         $newsId = $newsService->saveNewsInfo($newsInfo);
      }else{
          $newsService->updateNewsInfo($newsInfo);
      }
      exit($newsId);
  }
  elseif($action == 'delete_news'){
      $newsId = isset($_REQUEST['news_id']) ? trim($_REQUEST['news_id']) : '';
      if(empty($newsId)){
          exit(-1);
      }
      
      $sql = "delete from ty_news where news_id=$newsId";
      $newsService->getDb()->query($sql);
      exit($newsId);
  }
  
  
?>
